import { asyncRoutes, constantRoutes } from '@/router'
import { treeMenuByRoleId } from '@/api/role'
import Layout from '@/layout'
import { url } from '@/router/url'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 生成菜单路由
 * @param routes
 * @param data
 */
export function generaMenu(routes, data) {
  data.forEach(item => {
    const menu = {
      path: item.parentId === 0 ? '/' + item.name : item.name,
      component: item.parentId === 0 ? Layout : url.get(item.name),
      children: [],
      name: item.name,
      meta: { title: item.title, icon: item.icon }
    }
    if (item.parentId === 0 && item.child.length > 0) {
      console.log('item1', item)
      menu.redirect = '/' + item.name + '/' + item.child[0].name
    } else if (item.parentId === 0 && item.child.length === 0) {
      console.log('item2', item)
      menu.redirect = '/' + item.name + '/index'
      menu.children = [{
        path: 'index',
        component: url.get(item.name),
        name: item.name,
        meta: { title: item.title, icon: item.icon }
      }]
      delete menu.name
      delete menu.meta
    }
    if (item.child) {
      generaMenu(menu.children, item.child)
    }
    routes.push(menu)
  })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  console.log('路由组装完成', res)
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      console.log('组装路由=>角色', roles)
      const loadMenuData = []
      treeMenuByRoleId({ 'roles': roles }).then(response => {
        const { data } = response
        console.log('获取菜单', data)
        Object.assign(loadMenuData, data)
        const menuRoutes = []
        generaMenu(menuRoutes, loadMenuData)
        let accessedRoutes
        if (roles) {
          console.log('超级管理元=>角色', roles)
          accessedRoutes = menuRoutes.concat(asyncRoutes) || []
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
